// 在顶部引入
import * as echarts from "echarts";
import { useEffect, useRef } from "react";

interface MapChartProps {
  data?: any; // GeoJSON数据
  draw?: boolean;
  height?: number | string;
  colors?: string[];
  areaName?: string; // 区域名称
  title?: string; // 地图标题
  visualMapConfig?: {
    // 视觉映射配置
    min?: number;
    max?: number;
    text?: string[];
    left?: string;
    top?: string;
  };
  nameField?: string; // 从properties中提取的名称字段
  valueField?: string; // 从properties中提取的值字段
  defaultValue?: number; // 没有值时的默认值
  zoom?: number; // 地图缩放级别
  roam?: boolean | "scale" | "move"; // 是否开启缩放和平移
  showZoomControl?: boolean; // 是否显示缩放控件
  normalItemStyle?: Object;
  emphasisItemStyle?: Object;
  showRoam?: boolean;
  numericalUnits?: string;
  extraStyle?: string;
  markerPoints?: Array<{
    name: string;
    value: [number, number]; // 经纬度坐标
    customValue?: number; // 用于显示的数值
    symbolSize?: number; // 点大小
    itemStyle?: any; // 样式配置
  }>;
  alertPoints?: Array<{
    name: string;
    value: [number, number]; // 经纬度坐标
    customValue?: number; // 用于显示的数值
    symbolSize?: number; // 点大小
    itemStyle?: any; // 样式配置
  }>;
  showEffectScatter?: boolean; // 是否显示涟漪效果
}
// itemBgColors = ["#2ac6ff66","#00a8ff66","#41b0ff66","#148cff66","#308aff66","#507dff66","#6060ff66","#8040ff66"]
const MapChart = ({
  data,
  draw = true,
  height = 600,
  colors = ["#148cff", "#308aff", "#507dff", "#f00", "#0ff"],
  areaName = "巴南区",
  title = "社区分布图",
  visualMapConfig = { min: 0, max: 6, text: ["高", "低"] },
  nameField = "name",
  valueField = "value",
  defaultValue = 0,
  zoom = 1.2,
  showRoam = true,
  roam = true,
  showZoomControl = true,
  normalItemStyle = {
    areaColor: "#2ac6ff66", // 区域默认颜色
    borderColor: "#1cfeba", // 区域边界颜色
    borderWidth: 1, // 边界宽度
  },
  emphasisItemStyle = {
    areaColor: "#148cff66", // 高亮区域颜色
    shadowBlur: 10,
    shadowColor: "rgba(0, 0, 0, 0.5)",
  },
  numericalUnits = "",
  extraStyle = "",
  markerPoints = [],
  alertPoints = [],
  showEffectScatter = false,
}: MapChartProps) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  useEffect(() => {
    if (!draw || !chartRef.current) return;

    // 初始化图表
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }

    // 检查数据是否有效
    if (data && Array.isArray(data)) {
      // 注册地图数据
      const geoJson = {
        type: "FeatureCollection" as const,
        features: data,
      };

      // 注册地图
      echarts.registerMap(areaName || "巴南区", geoJson);

      // 准备显示数据
      const mapData = data.map((item: any) => ({
        name: item.properties?.name || "",
        value: item.properties?.value || 0,
      }));

      // 设置图表选项
      const option = {
        title: {
          text: areaName ? `${areaName}${title}` : title,
          left: "center",
          textStyle: {
            color: "#fff",
          },
        },
        visualMap: {
          min: visualMapConfig.min,
          max: visualMapConfig.max,
          text: visualMapConfig.text,
          realtime: false,
          calculable: true,
          inRange: {
            color: colors,
          },
          textStyle: {
            color: "#fff",
          },
          orient: "horizontal",
          left: visualMapConfig.left || "20%",
          top: visualMapConfig.top || "10%",
        },
        tooltip: {
          trigger: "item",
          formatter: function(params: any) {
            // 为所有元素统一显示格式
            if (params.componentSubType === 'scatter' || params.componentSubType === 'effectScatter') {
              // 对于标记点，只显示名称和"数值"，而不是经纬度数组
              return `${params.name}<br/>数值: ${params.data.customValue || 0}${numericalUnits}`;
            } else {
              // 对于地图区域
              return `${params.name}<br/>数值: ${params.value}${numericalUnits}`;
            }
          },
        },
        // 添加缩放控件
        toolbox: showZoomControl
          ? {
              show: true,
              orient: "vertical",
              left: "right",
              top: "center",
              feature: {
                dataView: { readOnly: false },
                restore: {},
                saveAsImage: {},
              },
            }
          : undefined,
        // 添加geo组件配置
        geo: {
          map: areaName || "巴南区",
          roam: showRoam,
          zoom: zoom,
          label: {
            show: true,
            color: "#fff",
          },
          itemStyle: {
            borderColor: "0BC265",
            shadowColor: "#182f68",
            shadowOffsetX: 0,
            shadowOffsetY: 20, //这里可以设置一下Y轴的阴影，比较有层次感
            borderWidth: 0, //设置外层边框
            areaColor: {
              type: "radial",
              x: 0.5,
              y: 0.5,
              r: 0.9,
              // 关键代码 会从offset：0到offset：1去过渡。
              // 我们可以增加其中的过渡颜色，在0和1之间加就行。
              // 比如：{
              //            offset: 0.5, color: 'green'
              //        },
              colorStops: [
                {
                  offset: 0,
                  color: "#0a3288",
                },
                {
                  offset: 1,
                  color: "rgba(27,130,183,1)",
                },
              ],
              global: false,
            },
          },
          emphasis: {
            label: {
              color: "#fff",
            },
            itemStyle: emphasisItemStyle,
          },
        },
        series: [
          {
            name: "社区数据",
            type: "map",
            map: areaName || "巴南区",
            zoom: zoom, // 设置地图缩放比例
            roam: showRoam, // 开启缩放和平移
            label: {
              show: true,
              color: "#fff",
              fontSize: 12, // 增大字体
              fontWeight: "bold", // 加粗
              position: "inside", // 标签位置在区域内部
              formatter: "{b}", // 显示区域名称
              textShadowColor: "#000", // 文字阴影颜色
              textShadowBlur: 3, // 文字阴影模糊度
            },
            itemStyle: normalItemStyle,
            data: mapData,
            emphasis: {
              // 强化区域高亮效果
              label: {
                color: "#ffffff",
                fontWeight: "bold",
                fontSize: 14,
              },
              itemStyle: emphasisItemStyle,
            },
          },

          // 添加普通标记点图层
          ...(markerPoints && markerPoints.length > 0
            ? [
                {
                  name: "标记点",
                  type: "scatter",
                  coordinateSystem: "geo",
                  symbol: "pin",
                  symbolSize: 30,
                  label: {
                    show: false,
                  },
                  itemStyle: {
                    color: "#0000FF",
                  },

                  data: markerPoints,
                  zlevel: 10,
                },
              ]
            : []),
          // 添加预警标记点图层（带涟漪效果）
          ...(alertPoints && alertPoints.length > 0 && showEffectScatter
            ? [
                {
                  name: "预警点",
                  type: "effectScatter",
                  coordinateSystem: "geo",
                  symbol: "pin",
                  symbolSize: 30,
                  label: {
                    show: true,
                    formatter: "{b}",
                    position: "right",
                    color: "#fff",
                  },
                  itemStyle: {
                    color: "#ff0000",
                  },
                  data: alertPoints,
                  // 涟漪效果配置
                  rippleEffect: {
                    brushType: "stroke",
                    scale: 2.5,
                    period: 4,
                  },
                  zlevel: 11,
                },
              ]
            : []),
        ],
      };

      // 设置选项并渲染
      chartInstance.current.setOption(option);
    }

    // 处理窗口大小变化事件
    const handleResize = () => {
      chartInstance.current?.resize();
    };

    window.addEventListener("resize", handleResize);

    // 清理函数
    return () => {
      window.removeEventListener("resize", handleResize);
      chartInstance.current?.dispose();
      chartInstance.current = null;
    };
  }, [
    data,
    draw,
    colors,
    areaName,
    title,
    visualMapConfig,
    nameField,
    valueField,
    defaultValue,
    zoom,
    roam,
    showZoomControl,
    markerPoints,
    alertPoints,
    showEffectScatter,
  ]);

  return (
    <div
      ref={chartRef}
      style={{ height: height }}
      className={`flex-1 ${extraStyle}`}
    ></div>
  );
};

export default MapChart;
